package com.hejie.userservice.repository;

import com.hejie.userservice.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    // 根据用户名查询用户
    Optional<User> findByUsernameAndDeletedFalse(String username);

    // 根据邮箱查询用户
    Optional<User> findByEmailAndDeletedFalse(String email);

    // 根据手机号查询用户
    Optional<User> findByPhoneAndDeletedFalse(String phone);

    // 检查用户名是否存在
    boolean existsByUsernameAndDeletedFalse(String username);

    // 检查邮箱是否存在
    boolean existsByEmailAndDeletedFalse(String email);

    // 检查手机号是否存在
    boolean existsByPhoneAndDeletedFalse(String phone);

    // 分页查询用户
    Page<User> findByDeletedFalse(Pageable pageable);

    // 根据角色分页查询用户
    Page<User> findByRoleAndDeletedFalse(@Param("role") User.UserRole role, Pageable pageable);

    // 更新用户状态
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.status = :status WHERE u.id = :id AND u.deleted = false")
    int updateUserStatus(@Param("id") Long id, @Param("status") User.UserStatus status);

    // 更新用户密码
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.password = :password WHERE u.id = :id AND u.deleted = false")
    int updateUserPassword(@Param("id") Long id, @Param("password") String password);

    // 逻辑删除用户
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.deleted = true WHERE u.id = :id")
    int logicallyDeleteUser(@Param("id") Long id);
}